import $service from "../../../service.js";
var prescription_id;
let prescriptionNo;
var that;
var ownLat; //自身的纬度
var ownLng; //自身的经度
const app = getApp()
Page({
  data: {
    ishospitalPre: '',
    hisType: $service.isHis,
    distanceFalg: false, //显示药店距离
    take_type: "1", //取货方式
    serialNum: "", //处方流水号
    hideSite: false, //地址栏显示
    show_choce: 0, //选择地址，药店
    prescriptionDetail: {}, // 处方信息
    prescriptionList: null, //药品列表
    price: "0.0", //金额
    drugStoreList: null, //药店列表
    siteList: [], //收货地址列表
    isDrugStoreList: true, //是否有合适药店
    isSiteList: true, //地址列表是否为空
    showAddress: false, //显示收货地址
    showDrugStore: false, //显示药店
    groupNo: '', // 药店id
    choiceDrugName: "", //选择药店名称
    choiceDrugAddress: "", //选择药店的地址
    storeFreight: '0.0', // 选择药店运费
    choiceDrugDistance: "", //选择药店的距离
    choiceSiteName: "", //收货人名称
    choiceSitePhone: "", //收货人电话
    choiceSiteAddress: "", //收货人地址
    choiceSiteId: "", // 收货地址ID
    choiceSiteAddressDetl: "", //收货人详细地址
    phone: '', // 取件人手机号
    userName: '', // 取件人姓名
    shopOutMessage: '', //缺货信息
    outDistanceMessage: '', //快递超出距离信息
    shippingFee: 0, //运费
    order_detail: [], //药店药品信息
    goodsAmount: 0, //药品金额
    orderAmount: 0, //订单总金额
    OutMessage: '', //自提错误信息
    GoodsPrice: 0, //药品信息
    array: [{text:'可选药店',value:2},{text:'不可选药店',value:1}], //药店筛选picker列表
    shopfilterIndex: "",
    keyword: "", //药店输入关键词
    isUser:"",  //是否是可选药店
  },

  async onLoad(e) {
    // let {latitude, longitude} = await wx.getLocation({type: 'wgs84'})
    // ownLat = latitude;
    // ownLng = longitude;
    prescription_id = e.prescription_id;
    prescriptionNo = e.prescriptionNo;
    // 新增地址后返回
    this.setData({
      serialNum: prescriptionNo,
      ishospitalPre: e.ishospitalPre,
      take_type: e.ishospitalPre == 0 && this.data.hisType ? 2 : 1,
      hideSite: e.ishospitalPre == 0 && this.data.hisType,
      showDrugStore: e.ishospitalPre == 0 && this.data.hisType ? true : false
    })
    e.ishospitalPre == 0 & this.data.hisType ? this.getPrescriptionInfoById() : this.getPrescriptioninfo()
  },

 
  onShow() {
    that = this.data;
    this.getReceivingAddress();
  },

  // 选项按钮
  radioChange: function (e) {
    var val = e.detail.value;
    // console.log(this.data.storeFreight)
    // console.log(this.data.orderAmount);
    this.setData({
      take_type: val,
      hideSite: val == 2 ? true : false,
    })
    if (this.data.orderAmount == 0) {
      var GoodsPrice = Number(this.data.prescriptionDetail.prescriptionPrice).toFixed(2)
      var price = val == '1' ? Number(this.data.prescriptionDetail.prescriptionPrice).toFixed(2) : this.data.prescriptionDetail.prescriptionPrice
    } else {
      this.whetherOrder()
      var GoodsPrice = Number(this.data.goodsAmount).toFixed(2)
      var price = Number(this.data.orderAmount).toFixed(2)
    }
    this.setData({
      price: price,
      GoodsPrice: GoodsPrice
    })
  },

  //获取处方详情
  getPrescriptioninfo() {
    app.http.getPrescriptioninfo({
      prescriptionNo: prescriptionNo
    }).then(res => {
      let price = Number(res.data.prescriptionPrice).toFixed(2)
      let GoodsPrice = Number(res.data.prescriptionPrice).toFixed(2)
      this.setData({
        prescriptionDetail: res.data,
        prescriptionList: res.data.prescriptionType === '1' ? res.data.chineseMedicineResqList : res.data.westernMedicineResqList,
        price: price,
        GoodsPrice: GoodsPrice
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  //input输入药店
  searchShop(e) {
    this.setData({
      keyword: e.detail.value
    })
    this.changDrugStore()
  },
  //picker选择
  bindPickerChange(e) {
    this.setData({
      isUser:this.data.array[e.detail.value].value,
      shopfilterIndex:e.detail.value
    })
    this.changDrugStore()
  },
  // 药店列表
  changDrugStore: function () {
    if (this.data.ishospitalPre == 0 && this.data.hisType) return
    console.log(ownLat,ownLng)
    this.setData({
      show_choce: 1
    })
    this.getLocation();
    let params = {
      keyword: this.data.keyword,
      use: this.data.isUser,
      prescriptionId: prescription_id
    }
    app.http.getShopList(params).then(res => {
      let {
        list
      } = res.data
      if (ownLat && ownLng) {
        list.forEach(i => {
          if (i.loc_x && i.loc_y) {
            i.distance = this.getDistance(ownLat, ownLng, i.loc_x, i.loc_y);
          }
        })
      }
      this.setData({
        drugStoreList: list,
        isDrugStoreList: false
      })
      console.log(list);
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 获取地址列表
  getReceivingAddress() {
    let params = {
      current: 1,
      size: 20
    }
    app.http.getReceivingAddress(params).then(res => {
      let siteList = res.data.list
      let {
        choiceSiteName,
        choiceSitePhone,
        choiceSiteAddress,
        choiceSiteId,
        choiceSiteAddressDetl,
        showAddress
      } = this.data;
      let isSite = ''
      siteList.find((i) => {
        isSite = i.id === this.data.choiceSiteId
      })
      if (!isSite) { // 判断地址有没有被删除 删除了则隐藏重新选择
        showAddress = false
        choiceSiteId = ''
      }
      siteList.forEach(item => {
        if (!this.data.choiceSiteId) { // 如果没有选择地址会选择默认地址
          if (item.addressDeft === '1') {
            choiceSiteName = item.userName;
            choiceSitePhone = item.userPhone;
            choiceSiteAddress = item.address;
            choiceSiteAddressDetl = item.addressDetl;
            choiceSiteId = item.id;
            showAddress = true
          }
        } else { // 如果已经选择了地址 地址被修改后 更新地址
          if (isSite && this.data.choiceSiteId === item.id) {
            choiceSiteName = item.userName;
            choiceSitePhone = item.userPhone;
            choiceSiteAddress = item.address;
            choiceSiteAddressDetl = item.addressDetl;
            showAddress = true
          }
        }
      })
      this.setData({
        siteList,
        choiceSiteId,
        choiceSiteName,
        choiceSitePhone,
        choiceSiteAddress,
        choiceSiteAddressDetl,
        showAddress
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 选择地址
  changeSite: function () {
    this.setData({
      show_choce: 2
    });
  },
  // 关闭弹窗
  showClose: function () {
    this.setData({
      show_choce: 0
    })
  },
  //增加新地址
  addressAdd: function () {
    wx.navigateTo({
      url: "../address_add/address_add"
    })
  },
  // 确认药店
  sureDrugStore: function (e) {
    console.log(e)
    let {
      group_address,
      group_name,
      distance,
      group_no,
      store_temp_freight,
      goods_check,
      recommend,
      order_detail
    } = e.currentTarget.dataset.info
    let orderArray = [];
    console.log(order_detail[0].goods_detail);
    let prescriptionList = this.data.prescriptionList
    order_detail[0].goods_detail.forEach((item, index) => {
      orderArray.push({
        "drugId": item.drug_id,
        "goodId": item.goods_id
      })
      prescriptionList[index].drugPrice = item.goods_price
    })
    if (that.take_type == '2') {
      if (goods_check == 1) {
        $service.showToast('所选药店缺少处方所需药品，请选择其他药店')
      } else {
        wx.showModal({
          title: '提示',
          content: '不同药房药品价格可能存在浮动，确定选择？',
          success: (res) => {
            if (res.confirm) {
              this.setData({
                groupNo: group_no,
                choiceDrugName: group_name,
                choiceDrugAddress: group_address,
                choiceDrugDistance: distance,
                showDrugStore: true,
                show_choce: 0,
                storeFreight: store_temp_freight,
                order_detail: orderArray,
                prescriptionList: prescriptionList
              });
              this.whetherOrder(res)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
      }
    } else {
      if (goods_check == 1) {
        $service.showToast('所选药店缺少处方所需药品，请选择其他药店')
      } else {
        wx.showModal({
          title: '提示',
          content: '不同药房药品价格可能存在浮动，确定选择？',
          success: (res) => {
            if (res.confirm) {
              //判断是否为缺货药店
              if (that.groupNo == group_no && that.shopOutMessage) {
                $service.showToast('所选药店缺少处方所需药品，请选择其他药店')
              } else {
                this.setData({
                  groupNo: group_no,
                  choiceDrugName: group_name,
                  choiceDrugAddress: group_address,
                  choiceDrugDistance: distance,
                  showDrugStore: true,
                  show_choce: 0,
                  storeFreight: store_temp_freight,
                  order_detail: orderArray,
                  prescriptionList: prescriptionList
                });
                this.whetherOrder(res)
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
      }
    }
  },
  // 确认收货地址
  sureAddress: function (e) {
    let data = e.currentTarget.dataset.site
    let choiceSiteName = data.userName;
    let choiceSitePhone = data.userPhone;
    let choiceSiteAddress = data.address;
    let choiceSiteAddressDetl = data.addressDetl;
    let choiceSiteId = data.id;
    wx.showModal({
      title: '提示',
      content: '确认选择？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            choiceSiteId,
            choiceSiteName,
            choiceSitePhone,
            choiceSiteAddress,
            choiceSiteAddressDetl,
            showAddress: true,
            show_choce: 0
          })
        }
        this.whetherOrder(res)
      }
    })
  },
  //判断货物库存和药店距离
  whetherOrder(res) {
    if (that.showAddress && that.showDrugStore) {
      console.log(res);
      let params = {
        "addressId": that.choiceSiteId,
        "deliveryMode": that.take_type,
        "money": that.prescriptionDetail.prescriptionPrice,
        "orderMessage": '',
        "prescriptionId": prescription_id,
        "storeId": that.groupNo,
        "phone": that.phone,
        "userName": that.userName,
        "type": 1,
        "drugInfoList": that.order_detail,
        "storeName": that.choiceDrugName
      }
      app.http.getPrescriptionOrder(params).then(res => {
        let shippingFee = res.data.shippingFee
        console.log(res.data.orderAmount);
        console.log(res.data.goodsAmount);
        var GoodsPrice = Number(res.data.goodsAmount).toFixed(2)
        var price = Number(res.data.orderAmount).toFixed(2)
        console.log(price);
        this.setData({
          price: price,
          OutMessage: '',
          outDistanceMessage: '',
          goodsAmount: res.data.goodsAmount,
          orderAmount: res.data.orderAmount,
          shippingFee: res.data.shippingFee,
          GoodsPrice,
        })
      }).catch(err => {
        console.log(err.msg);
        if (err.msg.includes('不支持自提')) {
          $service.showToast(err.msg)
          this.setData({
            OutMessage: err.msg
          })
        } else {
          $service.showToast(err.msg)
          this.setData({
            outDistanceMessage: err.msg
          })
        }
      })
    }
  },
  //保存
  save_order: function () {
    if (this.data.ishospitalPre == 0 && this.data.hisType) {
      this.addCflzHisPayMentInfo()
      return
    } 
    if ($service.isUndefinedAndEmpty(this.data.groupNo)) {
      $service.showToast('请选择药店');
      return false;
    }
    if (that.take_type == '3' && $service.isUndefinedAndEmpty(that.choiceSiteId) || that.take_type == '1' && $service.isUndefinedAndEmpty(that.choiceSiteId)) {
      $service.showToast('请选择收货地址！');
      return false;
    }
    if (that.take_type == '2') {
      if (this.data.OutMessage) {
        $service.showToast('所选药店不支持自提，请选择其他药店');
      } else {
        if (!that.userName) {
          $service.showToast('请填写取件人姓名');
          return
        }
        if (!that.phone) {
          $service.showToast('请输入手机号');
          return;
        }
        if (!$service.validateElement('mobile', that.phone)) {
          $service.showToast('请输入正确的手机号');
          return;
        }

        wx.showModal({
          title: '提示',
          content: '保存后不能修改, 确认保存吗?',
          success: (res) => {
            if (res.confirm) {
              wx.login({
                success: res => {
                  let params = {
                    "addressId": that.choiceSiteId,
                    "code": res.code,
                    "deliveryMode": that.take_type,
                    "money": that.price,
                    "orderMessage": '',
                    "prescriptionId": prescription_id,
                    "storeId": that.groupNo,
                    "phone": that.phone,
                    "userName": that.userName,
                    "type": 0,
                    "drugInfoList": that.order_detail,
                    "storeName": that.choiceDrugName
                  }
                  app.http.getPrescriptionOrder(params).then(res => {
                    wx.showToast({
                      title: '创建成功',
                      mask: true
                    })
                    setTimeout(() => {
                      wx.redirectTo({
                        url: '../order_msg/order_msg?prescription_id=' + res.data.orderSn
                      })
                    }, 1000)
                  }).catch(err => {
                    $service.showToast(err.msg)
                  })
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    } else {
      if (that.shopOutMessage || that.outDistanceMessage) {
        if (that.shopOutMessage) {
          $service.showToast('所选药店缺少处方所需药品，请选择其他药店')
        } else {
          $service.showToast('所选地址暂不支持配送，请更换地址')
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '保存后不能修改, 确认保存吗?',
          success: (res) => {
            if (res.confirm) {
              console.log(that.order_detail);
              wx.login({
                success: res => {
                  let params = {
                    "addressId": that.choiceSiteId,
                    "code": res.code,
                    "deliveryMode": that.take_type,
                    "money": that.price,
                    "orderMessage": '',
                    "prescriptionId": prescription_id,
                    "storeId": that.groupNo,
                    "phone": that.phone,
                    "userName": that.userName,
                    "type": 0,
                    "drugInfoList": that.order_detail,
                    "storeName": that.choiceDrugName
                  }
                  app.http.getPrescriptionOrder(params).then(res => {
                    wx.showToast({
                      title: '创建成功',
                      mask: true
                    })
                    setTimeout(() => {
                      wx.redirectTo({
                        url: '../order_msg/order_msg?prescription_id=' + res.data.orderSn
                      })
                    }, 1000)
                  }).catch(err => {
                    $service.showToast(err.msg)
                  })
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  },
  // 操作收货地址
  siteHandle(e) {
    let {
      id,
      type
    } = e.currentTarget.dataset
    let params = {
      id: id
    }
    if (type === 'updateReceivingAddress') {
      wx.navigateTo({
        url: "../address_add/address_add?id=" + id
      })
    } else {
      if (type === 'setDeftAddress') {
        params.userId = JSON.parse($service.getStore('userInfo')).id
      }
      app.http[type](params).then(res => {
        $service.showToast(res.msg)
        this.getReceivingAddress();
      }).catch(err => {
        $service.showToast(err.msg)
      })
    }
  },

  // 填写取件人信息
  inputChange(e) {
    let index = e.currentTarget.dataset.index
    let text = e.detail.value
    if (index == '0') {
      this.data.userName = text
    } else {
      this.data.phone = text
    }
    this.setData({
      userName: this.data.userName,
      phone: this.data.phone
    })
  },

  // 获取自身的经纬度
  getLocation() {
    
    var _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        ownLat = res.latitude;
        ownLng = res.longitude;
        _this.setData({
          distanceFalg: true
        })
      },
    })
  },
  //  计算距离
  Rad: function (d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    // lat1用户的纬度
    // lng1用户的经度
    // lat2商家的纬度 x
    // lng2商家的经度 y
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2); //保留两位小数
    // console.log('经纬度计算的距离:' + s)
    return s
  },

 // 廉江his院内处方创建订单
 addCflzHisPayMentInfo() {
  app.http.addCflzHisPayMentInfo({id: Number(prescription_id)}).then(res => {
    wx.showToast({
      title: '创建成功',
      mask: true
    })
    setTimeout(() => {
      wx.redirectTo({
        url: '../order_msg/order_msg?prescription_id=' + prescription_id + '&type=1'
      }) 
    }, 1000)
  }).catch(err => {
    $service.showToast(err.msg)
  })
 },

  // 获取廉江his院内处方详情
  getPrescriptionInfoById() {
    app.http.getPrescriptionInfoById({id: Number(prescription_id)}).then(res => {
      if (ownLat && ownLng) {
        this.data.choiceDrugDistance = this.getDistance(ownLat, ownLng, res.data.lat, res.data.lng);
      }
      this.setData({
        prescriptionList: res.data.prescriptionInfoVOList,
        choiceDrugAddress: res.data.hospitalAddress,
        choiceDrugDistance: this.data.choiceDrugDistance,
        GoodsPrice: res.data.prescriptionPrice,
        'prescriptionDetail.createTime': res.data.prescriptionAuditedDate,
        'prescriptionDetail.prescriptionType': res.data.prescriptionType,
        price: res.data.prescriptionPrice,
        "prescriptionDetail.patientName": res.data.patientName,
        choiceDrugName: res.data.hospitalName
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  }
})